package com.myrice.remote.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.myrice.remote.RemoteMethodCollection;
import com.myrice.remote.ServiceObject;
import com.myrice.util.POJO;

/**
 * 已注册的服务对象实现类
 * 
 * @author yiyongpeng
 * 
 */
public class DefaultServiceObject extends POJO implements ServiceObject {
	private String handle;
	private Object instance;
	private RemoteMethodCollection methods;

	public DefaultServiceObject() {
	}

	// public DefaultServiceObject(String handle, Object instance,
	// RemoteMethodCollection methods) {
	// this();
	// this.handle = handle;
	// this.instance = instance;
	// this.methods = methods;
	// }

	public DefaultServiceObject(String handle, Object instance,
			Class<?>... interfaces) {
		this();
		this.handle = handle;
		this.instance = instance;
		this.methods = new DefaultRemoteMethodCollection(handle, interfaces);
	}

	public void init() {
		try {
			Method method = this.instance.getClass().getMethod("init");
			method.invoke(instance);
		} catch (NoSuchMethodException e) {
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.getTargetException().printStackTrace();
		}
	}

	public void destroy() {
		try {
			Method method = this.instance.getClass().getMethod("destroy");
			method.invoke(instance);
		} catch (NoSuchMethodException e) {
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.getTargetException().printStackTrace();
		}
	}

	public Object getInstance() {
		return instance;
	}

	public RemoteMethodCollection getMethodCollection() {
		return this.methods;
	}

	public String getHandle() {
		return handle;
	}

	public Object getInvokeHandle() {
		return methods.getInvokeHandle();
	}

	public RemoteMethodCollection getMethods() {
		return methods;
	}

	public void setMethods(RemoteMethodCollection methods) {
		this.methods = methods;
	}

	public void setHandle(String handle) {
		this.handle = handle;
	}

	public void setInstance(Object instance) {
		this.instance = instance;
	}

}
